<template>
  <a v-if="record.asseApprove != 2" @click="dialog = true">
    <span>提交审批</span>
    <a-modal v-model="dialog" @ok="submit" okText="发送审批" :width="1000">
      <div class="flex justify-between mt-3">
        <p>审批状态：{{ getState(record.asseApprove) }}</p>
        <a-button @click="preview = !preview" :type="preview ? 'primary' : ''">{{
          preview ? '编辑' : '预览'
        }}</a-button>
      </div>
      <div class="rich-text-preview" v-html="text" v-show="preview"></div>
      <div v-show="!preview" id="editor"></div>
    </a-modal>
  </a>
  <span v-else>提交审批</span>
  <!-- <h1>
        上传附件：
        <a-upload :multiple="true" accept=".pdf" :file-list="fileList" @change="handleChange">
          <a-button> <a-icon type="upload" /> 上传文件 </a-button>
        </a-upload>
      </h1>
      <p class="text">支持扩展名：.pdf</p> -->
</template>
<script>
import { updataloanDelay, createRichText, getRichText } from '@/api/common'
import { asseAppState } from '@/dict'
import OSSClient from '@/utils/oss'
const client = new OSSClient()

export default {
  name: 'submitApply',
  props: ['record'],
  data() {
    return {
      dialog: false,
      editor: null,
      text: '',
      preview: false
    }
  },
  watch: {
    dialog(v) {
      if (v) {
        this.$nextTick(() => {
          this.editor || this.initEditor()
        })
      } else {
        this.editor && this.editor.destroy()
        this.editor = null
      }
    }
  },
  methods: {
    getState(v) {
      return asseAppState.find(el => el.value == v)?.text || '待审批'
    },
    async getRichText() {
      const res = await getRichText({
        relationId: this.record.id,
        relationType: 3
      })
      this.text = res.result.data?.[0]?.text
    },
    async submit() {
      var id = this.record.id
      await createRichText({
        relationId: id,
        relationType: 3,
        text: this.text
      })
      await updataloanDelay(id, { asseApprove: 5 })
      this.dialog = false
      this.$emit('update')
    },
    async initEditor() {
      const _this = this
      const editor = new wangEditor(`#editor`)
      // 配置 onchange 回调函数，将数据同步到 vue 中
      editor.config.onchange = newHtml => {
        this.text = newHtml
      }
      editor.config.customUploadImg = async function(resultFiles, insertImgFn) {
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法
        let url = await client.upload(resultFiles[0], _this.id, 1)
        insertImgFn(url)
      }
      // 创建编辑器
      editor.create()
      this.editor = editor
      await this.getRichText()
      editor.txt.append(this.text)
    }
  }
}
</script>
<style lang="css" scoped>
.text {
  margin: 15px 0 250px 100px;
  color: grey;
}
</style>
